//
//  StoryControllerView.m
//  iPing
//
//  Created by Thomas on 8/11/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "StoryControllerView.h"
//#import "TCSGgetSOLstory.h"
#import "TCSGgetLitStory.h"
#import "TCSGStory.h"
#import "TCSGDownloaderPlugins.h"
@interface StoryControllerView (private)
- (void)setHostsMenu;
- (NSMutableArray *)allBundles;
- (void)loadAllPlugins;

@end

@implementation StoryControllerView

- (void)awakeFromNib
{
	NSLog(@"awaking in controllerView");
	[self loadAllPlugins];
	[self setHostsMenu];
	[hostButton selectItemAtIndex:1];
	[self changeHost:nil];
	NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; 
	[nc addObserver:self 
           selector:@selector(displayText:) 
               name:TCSGLabelNot
             object:nil]; 
	theStoryListView	= [[SGStoryList alloc] init];
	[theStoryListView setManagedObjectContext:managedObjectContext];
	[theStoryListView retain];
	storyTag=0;
}
-(void)setHostsMenu
{

	[hostButton removeAllItems];
	int i;
	[hostButton addItemWithTitle:[NSString stringWithFormat:@"Literotica.com",nil]];
	[imageWell setImage:[NSImage imageNamed:@"litlogo"]];
	
	
	for (i=0;i<[instances count];i++)
	{
		[hostButton addItemWithTitle:[[instances objectAtIndex:i] hostName]];
	}
	
}
NSString *ext = @"sgdl";
NSString *appSupportSubpath = @"Application Support/Story Grabber/PlugIns";
- (NSMutableArray *)allBundles
{
    NSArray *librarySearchPaths;
    NSEnumerator *searchPathEnum;
    NSString *currPath;
    NSMutableArray *bundleSearchPaths = [NSMutableArray array];
    NSMutableArray *allBundles = [NSMutableArray array];
	
    librarySearchPaths = NSSearchPathForDirectoriesInDomains(
															 NSLibraryDirectory, NSAllDomainsMask - NSSystemDomainMask, YES);
	//NSLog(@"bundlePath: %@",[[NSBundle mainBundle] pathForResources
    searchPathEnum = [librarySearchPaths objectEnumerator];
    while(currPath = [searchPathEnum nextObject])
    {
        [bundleSearchPaths addObject:
		 [currPath stringByAppendingPathComponent:appSupportSubpath]];
    }
    [bundleSearchPaths addObject:
	 [[NSBundle mainBundle] builtInPlugInsPath]];
	//[bundleSearchPaths addObject:[[NSBundle mainBundle] resourcePath]];
	
    searchPathEnum = [bundleSearchPaths objectEnumerator];
    while(currPath = [searchPathEnum nextObject])
    {

        NSDirectoryEnumerator *bundleEnum;
        NSString *currBundlePath;
        bundleEnum = [[NSFileManager defaultManager]
					  enumeratorAtPath:currPath];
        if(bundleEnum)
        {
            while(currBundlePath = [bundleEnum nextObject])
            {
                if([[currBundlePath pathExtension] isEqualToString:ext])
                {
					[allBundles addObject:[currPath
										   stringByAppendingPathComponent:currBundlePath]];
                }
            }
        }
    }
	
    return allBundles;
}
- (void)loadAllPlugins
{
    NSMutableArray *bundlePaths;
    NSEnumerator *pathEnum;
    NSString *currPath;
    NSBundle *currBundle;
    Class currPrincipalClass;
    id currInstance;
	
    bundlePaths = [NSMutableArray array];
    if(!instances)
    {
        instances = [[NSMutableArray alloc] init];
    }
	
    [bundlePaths addObjectsFromArray:[self allBundles]];
	
    pathEnum = [bundlePaths objectEnumerator];
    while(currPath = [pathEnum nextObject])
    {
        currBundle = [NSBundle bundleWithPath:currPath];
        if(currBundle)
        {
            currPrincipalClass = [currBundle principalClass];
            if(currPrincipalClass &&
               [TCSGDownloaderPlugins plugInClassIsValid:currPrincipalClass])  // Validation
            {
                currInstance = [[currPrincipalClass alloc] init];
                if(currInstance)
                {
                    [instances addObject:[currInstance autorelease]];
                }
            }
        }
    }
	//NSLog(@"isntances:%i",[instances count]);
}
- (id)init 
{ 
    if (![super initWithNibName:@"StoryGrabber" bundle:nil]) 
        return nil; 
	
	
	li=0;
    return self; 
} 

- (void)dealloc
{
	theStoryListView	= nil;
	
	[[NSNotificationCenter defaultCenter] removeObserver:self];
	[theStoryListView	release];
	
	[super dealloc];
}
- (IBAction)doAddRandom:(id)pId
{
	TCSGePubCreator *epubCreate = [TCSGePubCreator createePubCompilationFromCode:@"FW_77238" withContext:managedObjectContext];
	[epubCreate createePub];
	//[[NSWorkspace sharedWorkspace] selectFile:[TCSGGeneralMethods fullStoryPathForHTMLCode:@"SOL_51230"] inFileViewerRootedAtPath:@""];
	[tableView reloadData];
}
#pragma mark IBActions
- (IBAction)addToLibrary:(id)pId
{
	[theStoryListView addCheckedToLibrary];
}
- (IBAction)changeHost:(id)pId
{
	switch ([hostButton indexOfSelectedItem]) 
	{
		/*case 0:
			NSLog(@"case: 0 in Host");
			storyTag=0;
			[imageWell setImage:[NSImage imageNamed:@"SOLlogo.png"]];
			break;*/
		case 0:
		{
			storyTag=1;
			[imageWell setImage:[NSImage imageNamed:@"litlogo.png"]];
			[shortTOC setEnabled:YES];
			break;
		}
		
		default:
		{
			storyTag=2;
			[imageWell setImage:[[instances objectAtIndex:([hostButton indexOfSelectedItem]-1)] hostImage]];
			if([[instances objectAtIndex:([hostButton indexOfSelectedItem]-1)] respondsToAuthor])
			{
				[shortTOC setEnabled:YES];
			}else
			{
				[shortTOC setEnabled:NO];
			}
			break;

		}
	}
}
- (IBAction)combineAll:(id)pId
{
	[[theStoryListView combineAll] writeToFile:[[saveField stringValue] stringByAppendingPathComponent:[[compileField stringValue] stringByAppendingPathExtension:@"html"]] atomically:YES encoding:NSUTF8StringEncoding error:nil];
	TCSGePubCreator *creator = [TCSGePubCreator createePubCompilationFromCode:@"SOL_44463" withContext:managedObjectContext];
	[creator createePub];
}
-(IBAction)doGet:(id)pId
{
	NSString *savePath = [saveField stringValue];
	NSString *IDval=[idField stringValue];
	BOOL isDir;
	if(running) //is it running
	{
		[self stopRunning];
	}
	else //not running yet
	{
		
		if([IDval isEqualToString:@""] || [IDval length] ==0) // is story ID specified
		{
			[labelField setStringValue:@"ERROR: Please specify a story ID"];
		}
		else if([savePath isEqualToString:@""] || [savePath length] ==0) // is there a save path specified
		{
			[labelField setStringValue:@"ERROR: Please specify a Save Path"];
		}
		else	
		{
			if(![[NSFileManager defaultManager] fileExistsAtPath:savePath]) //does folder exist
			{
				running =YES;
				[[NSFileManager defaultManager] createDirectoryAtPath:savePath attributes:nil];
			}
			else if([[NSFileManager defaultManager] fileExistsAtPath:savePath isDirectory:&isDir] && !isDir) // is foldername used
			{
				running=YES;
				[labelField setStringValue:@"ERROR: file already instead of folder at savepath, please move it"];
			}
			
			//Launch Thread
			if([shortTOC state])
			{
				NSThread* myThread = [[NSThread alloc] initWithTarget:self
															 selector:@selector(getAuthorStories:)
															   object:[idField stringValue]];
				[myThread start];
				
			}
			else
			{
				NSThread* myThread = [[NSThread alloc] initWithTarget:self
															 selector:@selector(getSingleStory:)
															   object:[idField stringValue]];
				[myThread start];
				
			}
			
			[self startRunning];
			[getButton setState:1];
			
		}
	}
}

-(IBAction)doOpenSaveFolder:(id)pId;
{	
	if(!running)
	{
		NSOpenPanel *tvarNSOpenPanelObj	= [NSOpenPanel openPanel];
		[tvarNSOpenPanelObj setMessage:@"Select Folder"];
		[tvarNSOpenPanelObj setCanChooseFiles:NO];
		[tvarNSOpenPanelObj setCanChooseDirectories:YES];
		[tvarNSOpenPanelObj setCanCreateDirectories:YES];
		NSInteger tvarNSInteger	= [tvarNSOpenPanelObj runModalForTypes:nil];
		if(tvarNSInteger == NSOKButton){
			[saveField setStringValue:[tvarNSOpenPanelObj filename]];
			[labelField setStringValue:@"Save Path set"];
		} else if(tvarNSInteger == NSCancelButton) {
			
			return;
		} else {
			return;
		}    
	}
}
- (IBAction)removeStoryFromTable:(id)pId
{
	[theStoryListView removeItemAtRow:[tableView selectedRow]];
	[tableView reloadData];
}
- (IBAction)moveDownInTable:(id)pId
{
	[theStoryListView moveItemAtRow:[tableView selectedRow] value:1];
	int row = [tableView selectedRow];
	if(row < ([theStoryListView numberOfItems]-1))
	{
		int i = [tableView selectedRow];
		[tableView selectRow:(i+1) byExtendingSelection:NO];
	}
	[tableView reloadData];
}
- (IBAction)moveUpInTable:(id)pId
{
	//int action=-1;
	int row = [tableView selectedRow];
	[theStoryListView moveItemAtRow:row value:-1];
	
	if(row != 0)
	{
		int i = [tableView selectedRow];
		[tableView selectRow:(i-1) byExtendingSelection:NO];
	}
	[tableView reloadData];
}
#pragma mark View Controllers
- (void)displayText:(NSNotification *)note
{
	[labelField setStringValue:[note object]];
}
-(void)startRunning
{
	running = YES;
	[[NSNotificationCenter defaultCenter] postNotificationName:TCSGRunning object:[NSNumber numberWithBool:YES]];
	[getButton setState:1];
	[saveButton setEnabled:NO];
	[longTOC	setEnabled:NO];
	[hostButton	setEnabled:NO];
	[moreInfoButton		setEnabled:NO];
	[shortTOC	setEnabled:NO];
	[removeButton		setEnabled:NO];
	[compileButton		setEnabled:NO];
	[upButton	setEnabled:NO];
	[downButton	setEnabled:NO];
	[saveField	setEnabled:NO];
	[idField	setEnabled:NO];
	[AddLibButton	setEnabled:NO];
	
}
-(void)stopRunning
{
	
	running = NO;
	[[NSNotificationCenter defaultCenter] postNotificationName:TCSGRunning object:[NSNumber numberWithBool:NO]];
	[getButton setState:0];
	[saveButton setEnabled:YES];
	[longTOC	setEnabled:YES];
	[hostButton	setEnabled:YES];
	[moreInfoButton		setEnabled:YES];
	[shortTOC	setEnabled:YES];
	[removeButton		setEnabled:YES];
	[compileButton		setEnabled:YES];
	[upButton	setEnabled:YES];
	[downButton	setEnabled:YES];
	[saveField	setEnabled:YES];
	[idField	setEnabled:YES];
	[AddLibButton		setEnabled:YES];
}
#pragma mark Download Selectors
- (void)getAuthorStories:(NSString *)authorID
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	id get;
	switch (storyTag) 
	{
		case kSCHostSOL:

			//[self sOLAuthorDL:authorID];
			get = [[TCSGgetSOLstory alloc] init];
			break;
		case kSCHostLIT:
			get = [[TCSGgetLitStory alloc] init];
			break;
		default:
			get = [instances objectAtIndex:([hostButton indexOfSelectedItem]-1)];
			break;
	}
	NSArray	*authorStories	= [get getStoriesArrayForAuthor:authorID];
	int i;
	for(i=0;i<[authorStories count];i++)
	{
		NSDictionary *storyDict = [get getStory:[authorStories objectAtIndex:i]];
		if(running)
		{
			[self addStoryToList:storyDict];
			
		}
		if([moreInfoButton state] && running)
		{
			
			[theStoryListView addExtraInfo:[get getMoreInfoForID:[authorStories objectAtIndex:i]] forRow:([theStoryListView numberOfItems]-1)];
		}
		[tableView reloadData];
	}
	[self stopRunning];
	//[tableView reloadData];
	[pool release];
	
}
-(void)getSingleStory:(NSString *)storyID
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	id get;
	switch ([hostButton indexOfSelectedItem]) 
	{
		case kSCHostSOL:
			//NSLog(@"case: 0");
			get = [[TCSGgetSOLstory alloc] init];
			//[self getSOLStory:storyID];
			break;
		case kSCHostLIT:
			//NSLog(@"case: 1");
			get = [[TCSGgetLitStory alloc] init];
			break;
		default:
			
			get = [instances objectAtIndex:([hostButton indexOfSelectedItem]-1)];
			break;
	}
	if([get respondsToSelector:@selector(getStory:)])
	{
		NSLog(@"here1");
		NSDictionary *story = [get getStory:storyID];
		[self addStoryToList:story];
	}
	[self stopRunning];
	[getButton setState:0];
	[tableView reloadData];
	[pool release];
	
}


#pragma mark StoryList Interactions
- (BOOL)addStory:(int)row	{return [theStoryListView checkForRow:row withKey:CHECKKEY];}

- (void)addStoryToList:(NSDictionary *)storyDict
{
	NSArray *keys = [storyDict allKeys];
	if([keys containsObject:STORYKEY] && [keys containsObject:HOSTKEY] && [keys containsObject:AUTHORKEY] && [keys containsObject:IDKEY] && [keys containsObject:TITLEKEY])
	{
		if([keys containsObject:HTMLCODEKEY])
		{
			[theStoryListView addStory:[storyDict objectForKey:STORYKEY] 
							 withTitle:[storyDict objectForKey:TITLEKEY] 
							withAuthor:[storyDict objectForKey:AUTHORKEY] 
							  withHost:[storyDict objectForKey:HOSTKEY] 
								withID:[storyDict objectForKey:IDKEY] 
							 withCheck:[NSNumber numberWithBool:YES]
						  withHTMLCode:[storyDict objectForKey:HTMLCODEKEY]];
		}
		else
		{
			[theStoryListView addStori:[storyDict objectForKey:STORYKEY] 
							 withTitle:[storyDict objectForKey:TITLEKEY] 
							withAuthor:[storyDict objectForKey:AUTHORKEY] 
							  withHost:[storyDict objectForKey:HOSTKEY] 
								withID:[storyDict objectForKey:IDKEY] 
							 withCheck:[NSNumber numberWithBool:YES]];
		}
		
		//NSLog(@"array: %@",[storyDict objectForKey:ARRAYKEY]);
		//[theStoryListView addStoriesArray:[storyDict objectForKey:ARRAYKEY] forRow:([theStoryListView numberOfItems]-1)];
		[theStoryListView addAddionalInfo:storyDict forRow:([theStoryListView numberOfItems]-1)];
	}
	else
	{
		[TCSGGeneralMethods setLabelField:@"Improperly Formatted Story Dictionary"];
	}
}

#pragma mark tableView Delegate Methods

- (id)tableView:(NSTableView *)tv 
objectValueForTableColumn:(NSTableColumn *)tableColumn 
			row:(int)row 
{ 
	
	NSArray *columns = [NSArray arrayWithObjects:@"ID",@"Title",@"Author",@"check",@"Host",@"DL",nil];
	long column = [columns indexOfObject:[tableColumn identifier]];
	NSDictionary *storyDict = [theStoryListView getDictForRow:row];
	NSString *v;
	switch (column) {
		case 0:
			v=[storyDict objectForKey:IDKEY];
			break;
		case 1:
			v=[storyDict objectForKey:TITLEKEY];
			break;
		case 2:
			v=[storyDict objectForKey:AUTHORKEY];
			break;
		case 4:
			v=[storyDict objectForKey:HOSTKEY];
			break;
		default:
			v=@"";
			break;
	}
    return v; 
} 
- (BOOL)tableView:(NSTableView *)tv 
  shouldTrackCell:(NSCell *)cell 
   forTableColumn:(NSTableColumn *)tableColumn 
			  row:(NSInteger)row
{
	BOOL tracking = NO;
	if([[tableColumn identifier] isEqualToString:@"DL"])
	{
		tracking =YES;
		[theStoryListView switchCheck:CHECKKEY forRow:row];
		
	}
	return YES;
}

- (int)numberOfRowsInTableView:(NSTableView *)tv 
{ 
    return [theStoryListView numberOfItems]; 
}




- (void)tableView:(NSTableView *)tv willDisplayCell:(id)aCell forTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex
{
	if([[aTableColumn identifier] isEqualToString:@"DL"])
	{
		[aCell setState:[self addStory:rowIndex]];
	}
}


-(NSString *)tableView:(NSTableView *)aTableView 
		toolTipForCell:(NSCell *)aCell 
				  rect:(NSRectPointer)rect 
		   tableColumn:(NSTableColumn *)aTableColumn 
				   row:(NSInteger)row 
		 mouseLocation:(NSPoint)mouseLocation
{
	NSString *returnString=@"";
	if([[aTableColumn identifier] isEqualToString:@"DL"])
	{
		returnString = @"Determines if the Story Should be Compiled";
	}
	else
	{
		NSDictionary *tempDict = [theStoryListView getDictForRow:row];
		//[tempDict writeToFile:@"/Users/tom/Desktop.plist" atomically:YES];
		if([[tempDict allKeys] containsObject:@"Summary"]){ returnString = [tempDict objectForKey:@"Summary"];/*NSLog(@"returnString: %@",[tempDict objectForKey:@"Summary"]);*/}
		else { returnString = @"Summary Not Available";}
	}
	return returnString;	
}

@end
